#!/usr/bin/lua

require "luarocks.require"
require "xmlreader"

local ROOT = os.getenv("HOME").."/.landroid"
local TRTEMPLATE = ROOT .. "/Files/TRTemplate.scala"
local Resources = {}
local ResourcesN = 0

local function make_directory (path)
	local pipe = io.popen("mkdir -p " .. path .. " && echo 0 || echo 1")
	if pipe:read("*l") == 1 then
		pipe:close()
		return false, "Error creating directory " .. path

	end
	pipe:close()
	return true
end

local function addResource (type ,id)
	print(string.format("Adding <%s> %s", type,id))
	Resources[id] = type
    ResourcesN = ResourcesN + 1
end

local function genVals ()
	local str = ""
	for id, type in pairs(Resources) do
		str = string.format("%s   val %s = TypedResource[android.widget.%s](R.id.%s)\n",
			str, id, type, id)
	end
	return str
end

local function writeTRFile (gendir, output, package)
	if ResourcesN == 0 then
		print("No needed TR class")
		return true
	end

	local fd, err = io.open(TRTEMPLATE, "r")
	if not fd then
		return nil, err
	end
	local buff = fd:read("*a")
	fd:close()

	local str = ""
	for p in package:gmatch("[^%.]+") do
		str = string.format("%s/%s", str, p)
	end
	str = string.format("%s/%s/%s", gendir,str,output)

	print("Writing file " .. str)
	
	fd, err = io.open(str,"w")
	if not fd then
		return nil, err
	end

	fd:write(string.format(buff, package, genVals()))
	fd:close()
end


local function main (argc, argv)
	if argc < 4 then
		print("Usage: GenerateTR.lua layout.xml outputdir output.scala package")
		os.exit(1)
	end
	local gendir = argv[1]
	local output = argv[2]
	local package = argv[3]
    for i=4, argc do
        local file = argv[i]
        print("Processing file: " .. file)
        local r = xmlreader.from_file(file)

        while (r:read()) do
            local element = nil
            local id = nil
            if r:node_type() == 'element' then
                element = r:name()
                while(r:move_to_next_attribute()) do
                    if r:name() == "android:id" then
                        id = r:value()
                        if id:match("^@") then
                            if id:match("^@%+id/") then -- new id
                                local _, n = id:find("^@%+id/")
                                addResource(element, id:sub(n+1, id:len()))
                            else
                            end
                        end
                    end
                end
            end
        end
    end
	local _, err = writeTRFile(gendir, output, package)
	if err then
		print("ERROR: " .. err)
	end
end

main(#arg, arg)
